package com.hongtech.framework.interceptor;

import com.hongtech.common.bean.Token;
import com.hongtech.common.enums.Action;
import com.hongtech.common.util.HttpUtils;
import com.hongtech.common.util.TokenUtil;
import com.hongtech.framework.anno.Login;
import com.hongtech.modules.system.service.SysMenuService;
import com.hongtech.modules.system.vo.TreeMenuVO;
import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) {

        if (handler instanceof HandlerMethod) {
            // 登录验证
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Login login = method.getAnnotation(Login.class);
            if (login != null && login.action() == Action.Skip) {
                return true;
            }
            // 正常执行
            Token token = TokenUtil.getToken(request);
            if (token == null) {
                if (HttpUtils.isAjax(request)) {
                    HttpUtils.ajaxStatus(response, 302, "{\"code\":\"1\",\"msg\":\"未登录或登录超时，请重新登录。\"}");
                } else {
                    TokenUtil.clearRedirectLogin(request, response);
                }
                return false;
            } else {
                // 当前用户的菜单
                List<TreeMenuVO> treeMenus = sysMenuService.listTreeMenuByUserId(token.getUid());
                request.setAttribute("treeMenus", treeMenus);
                // 当前用户的权限
                List<String> buttonList = sysMenuService.listMenuIdsByUserId(token.getUid());
                request.setAttribute("permissions", buttonList);
            }
        }
        return true;
    }

}
